import { beforeSave, column, hasOne } from '@adonisjs/lucid/orm'
import type { HasOne } from '@adonisjs/lucid/types/relations'
import CommonBaseModel from '#common/base_model'
import Dict from '#models/dict'
import { md5 } from '#utils/hash'

export default class User extends CommonBaseModel {
  @column()
  declare fkRoleId: number | null

  @column()
  declare fkSourceId: number | null

  @column()
  declare fkDeptId: number | null

  @column()
  declare fkPostId: number | null

  @column()
  declare userName: string

  @column({ serializeAs: null })
  declare password: string

  @beforeSave()
  static async hashPassword(user: User) {
    if (user.$dirty.password) user.password = md5(user.password)
  }

  @column()
  declare nickName: string

  @column()
  declare phone: string

  @column()
  declare openid: string

  @column()
  declare email: string

  @column()
  declare avatarUrl: string

  @column()
  declare sex: number

  @column()
  declare status: number

  @column()
  declare keywords: string

  @column({ isPrimary: false })
  declare loginShopId: number

  @column()
  declare memo: string

  @column()
  declare remember_me_token: string

  @hasOne(() => Dict)
  declare role: HasOne<typeof Dict>

  @hasOne(() => Dict)
  declare source: HasOne<typeof Dict>

  @hasOne(() => Dict)
  declare dept: HasOne<typeof Dict>

  @hasOne(() => Dict)
  declare post: HasOne<typeof Dict>
}
